<template>
    <el-container direction="vertical">
        <Header/>
        <el-container class="auto-width" direction="vertical">
            <el-main>
                <el-form id="userForm" :model="userForm" status-icon :rules="rules" label-position="right" ref="userForm" label-width="80px">
                    <el-form-item label="邮箱" prop="email">
                        <el-input type="text" v-model="userForm.email" autocomplete="off" placeholder="登录邮箱地址" :disabled="needVerify"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="pass">
                        <el-input type="password" v-model="userForm.pass" autocomplete="off" placeholder="长度6~16 打死都不能告诉别人 >o< " :disabled="needVerify"></el-input>
                    </el-form-item>
                    <el-form-item label="验证码" prop="verifyCode" v-if="needVerify">
                        <el-input type="text" v-model="userForm.verifyCode" autocomplete="off" placeholder="账户尚未激活，请输入验证码！">
                            <el-button slot="append" title="重发验证码" @click="resendCode()" :disabled="codeCD > 0"><i v-show="codeCD <= 0" class="el-icon-refresh"></i><span v-show="codeCD > 0">{{codeCD}}s</span></el-button>
                        </el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm('userForm')">提交</el-button>
                        <el-button @click="resetForm('userForm')">重置</el-button>
                        <el-link type="primary" style="margin-left: 10px" @click="goReg">尚未注册？</el-link>
                    </el-form-item>
                </el-form>
            </el-main>
        </el-container>
        <Footer/>
    </el-container>
</template>

<script>
    import UserService from '../services/user.service';
    import Header from '../components/Header';
    import Footer from '../components/Footer';
    import Loading from '../utils/loading';

    export default {
        name: 'Login',
        components: {Header, Footer},
        props: {},
        data() {
            return {
                needVerify: false,
                codeCD: 0,
                userForm: {
                    email: '',
                    pass: '',
                    verifyCode: '',
                },
                rules: {
                    verifyCode: [
                        {required: true, message: '验证码不能为空', trigger: 'blur'},
                        {len: 6, message: '长度在6个字符', trigger: 'blur'},
                    ],
                    email: [
                        {
                            required: true,
                            message: '请输入邮箱',
                            trigger: 'blur',
                        },
                        {
                            type: 'email',
                            message: '请输入有效的邮箱地址',
                            trigger: ['blur'],
                        },
                    ],
                    pass: [
                        {
                            required: true,
                            validator: (rule, value, callback) => {
                                if (value === '') {
                                    callback(new Error('请输入密码'));
                                } else {
                                    callback();
                                }
                            }
                            , trigger: 'blur',
                        },
                        {min: 6, max: 16, message: '长度在6到16个字符', trigger: 'blur'},
                    ],
                },
            };
        },
        methods: {
            goReg() {
                this.$router.push('/reg');
            },

            codeCdStart() {
                this.codeCD = 60;
                const self = this;
                const cd = setInterval(() => {
                    self.codeCD = self.codeCD - 1;
                    if (self.codeCD <= 0) {
                        clearInterval(cd);
                    }
                }, 1000);
            },

            async resendCode() {
                if (this.codeCD > 0) {
                    return;
                }
                Loading.showLoad('请稍后');
                let result = await UserService.resendCode(this.userForm);
                if (result.code === 0) {
                    this.$message.error(result.msg);
                } else {
                    this.$message.success('验证码已发送！');
                    this.codeCdStart();
                }
                Loading.hideLoad();
            },
            submitForm(formName) {
                this.$refs[formName].validate(async (valid) => {
                    if (valid) {
                        Loading.showLoad('请稍后');
                        let result = await UserService.login(this.userForm);
                        if (result.code === 0) {
                            this.$message.error(result.msg);
                        } else {
                            if (result.data.verified === false) {
                                this.$message.error('账户尚未激活，请输入验证码！');
                                this.needVerify = true;
                            } else {
                                this.$message.success('登录成功！');
                                this.$store.commit('setUser', result.data.user);
                                this.$store.commit('setToken', result.data.token);
                                this.$store.commit('setRole', result.data.role);
                                this.$router.push('/');
                            }
                        }
                        Loading.hideLoad();
                    } else {
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
        },
    };
</script>

<style scoped lang="scss">
    main {
        width: 100% !important;
        margin: 5% auto;
        max-width: 540px;
        border-radius: 2px;
        border: 1px solid #eee;
        box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    }
</style>
